<script setup lang="ts">
import { ref, toRaw, watch } from "vue";
import { useI18n } from "vue-i18n";

import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import D2Related from "@/views/dataCenter/relateddata/component/D2Related.vue";
import D3Related from "@/views/dataCenter/relateddata/component/D3Related.vue";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { getTimeRecentOptions, getTimeTypeOptions, pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useRoute } from "vue-router";
import { useLogic } from "@/views/system/user/logic/logic";
import { getDistributeTableOptionsApi } from "@/api/clusters/distributeTables";
import { getProductListApi } from "@/api/products/product";
import { getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { handleTree } from "@/utils/tree";
import { getDeviceOptionsApi } from "@/api/products/device";
import { ElMessage } from "element-plus";

const {t} = useI18n();

defineOptions({
  name: "relateddata"
});

const selected = ref(0);

function tabClick({ index }) {
  selected.value = index;
}

const listComponents = [
  {
    key: "d2related",
    title: t('datacenter.relateddataPage.d2Related'),
    component: D2Related
  },
  {
    key: "d3related",
    title: t('datacenter.relateddataPage.d3Related'),
    component: D3Related
  },
];

const pageSizeOps = ref(pageSizeOptions)
const route = useRoute();
const storeInfo = useUserStore()
const {deptId}= storeToRefs(storeInfo)

// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deptId: deptId.value,  //初始部门id
  productId: undefined,
  productKey: undefined,
  deviceGroupId: undefined,
  deviceNos:[],
  page:1,
  pageSize:500,
  timeType: 0 ,  // 0时间段 1最近时间
  timeRange: [],
  recent: 60,
  distributeTableId: undefined,
  interpolatePoints: 1000, // 插值点数
});

let productList = [];
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const deviceNoOptions = ref([])
const distributeTableOptions = ref([]);

const loadDistributeTableOptions = async () => {
  const { code, data } = await getDistributeTableOptionsApi(searchParams.value.deptId,'id', 'table');
  if (code === 0 && data) {
    distributeTableOptions.value = data.options;
  }
};

watch(()=>route.query,(newValue)=>{
  if (route.query.distributeTableId && Number(route.query.distributeTableId)>0) {
    searchParams.value.distributeTableId = Number(route.query.distributeTableId);
  }
  if (route.query.deptId && Number(route.query.deptId)>0) {
    searchParams.value.deptId = Number(route.query.deptId);
  }
  setTimeout(()=>{
    reloadThisPage()
  },5)
},{immediate:true,deep:true});

const reloadThisPage = async () => {
  await loadDistributeTableOptions();
  await getDeptTree()
  const productOptionsRes = await getProductListApi({
    pageSize:500,
    page:1,
    wheres:{
      openStatus:1,
    },
  })
  if(productOptionsRes.code == 0){
    productList = productOptionsRes.data.list ? productOptionsRes.data.list : [];
    productOptions.value = [
      ...productOptionsRes.data.list.map(option => ({
        val: option.id,
        label: option.name
      }))
    ];
  }
  await reLoadDeviceGroups()
}

const reLoadDeviceGroups = async ()=>{
  const req = new Map;
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi(req)
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
}

const reLoadDevices = async ()=>{
  const req = {
    fieldKey:"deviceNo",
    fieldLabel:"name",
  };
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  if(searchParams.value.productId){
    req.productId = searchParams.value.productId;
  }
  if(searchParams.value.deviceGroupId){
    req.deviceGroupId = searchParams.value.deviceGroupId;
  }
  deviceNoOptions.value = [];
  const deviceOptionsRes = await getDeviceOptionsApi(req)
  if(deviceOptionsRes.code == 0){
    deviceNoOptions.value = deviceOptionsRes.data.options;
  }
}
const timeTypeOptions = ref(getTimeTypeOptions());
const recentOptions = ref(getTimeRecentOptions())


const searchFields = ref([
  {
    prop: "productId",
    name: t('datacenter.relateddataPage.product'),
    type: "select",
    clearable: false,
    isHidden: false,
    formOptions: productOptions
  },
  {
    prop: "interpolatePoints",
    name: t('datacenter.relateddataPage.interpolatePoints'),
    type: "select",
    clearable: false,
    isHidden: false,
    formOptions: [
      { val: 100, label: "100" },
      { val: 200, label: "200" },
      { val: 500, label: "500" },
      { val: 1000, label: "1000" },
      { val: 2000, label: "2000" },
      { val: 3000, label: "3000" },
      { val: 5000, label: "5000" },
      { val: 10000, label: "10000" },
      { val: 20000, label: "20000" }
    ]
  },
  {
    prop: "deviceNos",
    name: t('datacenter.relateddataPage.deviceNo'),
    type: "multiSelect",
    clearable: true,
    isHidden: false,
    formOptions: deviceNoOptions
  },
  {
    prop: "timeType",
    name: t('datacenter.relateddataPage.timeType'),
    type: "select",
    clearable: false,
    isHidden: false,
    formOptions: timeTypeOptions
  },
  {
    prop: 'timeRange',
    name: t('datacenter.relateddataPage.timeRange'),
    type: 'datetimeRange',
    clearable: true,
    isHidden: false,
  },
  {
    prop: 'recent',
    name: t('datacenter.relateddataPage.recentTime'),
    type: 'select',
    formOptions: recentOptions,
    clearable: true,
    isHidden: true,
  },
  {
    prop: 'deptId',
    name: t('datacenter.relateddataPage.dept'),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: 'distributeTableId',
    name: t('datacenter.relateddataPage.distributeTable'),
    type: 'select',
    clearable: true,
    isHidden: false,
    formOptions: distributeTableOptions
  },
  {
    prop: 'deviceGroupId',
    name: t('datacenter.relateddataPage.deviceGroup'),
    type: 'cascader',
    cascaderOptions: deviceGroupOptions,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
])

const handleChange = (e: any) => {
  console.log(e)
  if(e.productId != searchParams.value.productId){
    searchParams.value.productId = e.productId
    searchParams.value.deviceNos = []
    searchParams.value.productKey = productList.find(item => item.id === e.productId)?.productKey || '';
    reLoadDevices()
  }
  if(e.deptId != searchParams.value.deptId){
    searchParams.value.deptId = e.deptId
    reLoadDeviceGroups()
    reLoadDevices()
  }
  if(e.deviceGroupId != searchParams.value.deviceGroupId){
    searchParams.value.deviceGroupId = e.deviceGroupId
    reLoadDevices()
  }
  if(e.timeType == 0){
    searchFields.value.map((item,index) => {
      if(item.prop == "timeRange"){
        searchFields.value[index].isHidden = false
      }
      if(item.prop == "recent"){
        searchFields.value[index].isHidden = true
      }
    })
  }else{
    searchFields.value.map((item,index) => {
      if(item.prop == "timeRange"){
        searchFields.value[index].isHidden = true
      }
      if(item.prop == "recent"){
        searchFields.value[index].isHidden = false
      }
    })
  }
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  searchParams.value.productKey = productList.find(item => item.id === e.productId)?.productKey || '';
}

const handleSearch = (e:any) => {
  console.log(e)
}

const handleReset = (e:any) => {
  console.log(e)
}

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=5
          @search="handleSearch"
          @change="handleChange"
          @reset="handleReset"
        />
      </div>
    </template>

    <el-tabs @tab-click="tabClick">
      <template v-for="(item, index) of listComponents" :key="item.key">
        <el-tab-pane :lazy="true">
          <template #label>
            <span
              v-tippy="{
                maxWidth: 'none',
                content: `${item.title}`
              }"
            >
              {{ item.title }}
            </span>
          </template>
          <keep-alive>
            <component
              :is="item.component"
              :key="item.key"
              v-show="selected == index"
              :deviceOptions="deviceNoOptions"
              :params="searchParams"
            />
          </keep-alive>
        </el-tab-pane>
      </template>
    </el-tabs>

  </el-card>
</template>

<style scoped lang="scss">

</style>

